import {defineStore} from 'pinia'
import {computed, ref} from 'vue'
import {
    createCategory as createCategoryApi,
    getCategoryDetail as getCategoryDetailApi,
    getCategoryList as getCategoryListApi,
    getCategoryTree as getCategoryTreeApi,
    updateCategory as updateCategoryApi
} from '@/api/category'

/**
 * 分类管理Store
 * 管理商品分类列表、分类详情、分类状态等数据
 */
export const useCategoryStore = defineStore('category', () => {
    // 状态
    const categories = ref([])
    const categoryTree = ref([])
    const currentCategory = ref(null)
    const loading = ref(false)
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)

    // 计算属性
    const categoryCount = computed(() => categories.value.length)
    const hasCategories = computed(() => categories.value.length > 0)

    /**
     * 获取分类列表（平铺展示）
     * @param {Object} params 查询参数
     */
    const getCategoryList = async (params = {}) => {
        loading.value = true
        try {
            const response = await getCategoryListApi({
                current: currentPage.value,
                size: pageSize.value,
                ...params
            })

            if (response.data) {
                categories.value = response.data.records || []
                total.value = response.data.total || 0
                currentPage.value = response.data.current || 1
            }

            return response
        } catch (error) {
            console.error('获取分类列表失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 获取分类树（用于下拉选择）
     */
    const getCategoryTree = async () => {
        try {
            const response = await getCategoryTreeApi()
            if (response.data) {
                categoryTree.value = response.data
            }
            return response
        } catch (error) {
            console.error('获取分类树失败:', error)
            throw error
        }
    }

    /**
     * 获取分类详情
     * @param {number} id 分类ID
     */
    const getCategoryDetail = async (id) => {
        loading.value = true
        try {
            const response = await getCategoryDetailApi(id)
            if (response.data) {
                currentCategory.value = response.data
            }
            return response
        } catch (error) {
            console.error('获取分类详情失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 创建分类
     * @param {Object} categoryData 分类数据
     */
    const createCategory = async (categoryData) => {
        loading.value = true
        try {
            const response = await createCategoryApi(categoryData)
            // 创建成功后刷新列表和树
            await Promise.all([getCategoryList(), getCategoryTree()])
            return response
        } catch (error) {
            console.error('创建分类失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 更新分类
     * @param {number} id 分类ID
     * @param {Object} categoryData 分类数据
     */
    const updateCategory = async (id, categoryData) => {
        loading.value = true
        try {
            const response = await updateCategoryApi(id, categoryData)
            // 更新成功后刷新列表和树
            await Promise.all([getCategoryList(), getCategoryTree()])
            return response
        } catch (error) {
            console.error('更新分类失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 删除分类
     * @param {number} id 分类ID
     */
    const deleteCategory = async (id) => {
        loading.value = true
        try {
            const response = await request.delete(`/admin/categories/${id}`)
            // 删除成功后刷新列表和树
            await Promise.all([getCategoryList(), getCategoryTree()])
            return response
        } catch (error) {
            console.error('删除分类失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 更新分类状态
     * @param {number} id 分类ID
     * @param {number} status 状态值
     */
    const updateCategoryStatus = async (id, status) => {
        loading.value = true
        try {
            const response = await request.put(`/admin/categories/${id}/status`, {status})
            // 更新成功后刷新列表
            await getCategoryList()
            return response
        } catch (error) {
            console.error('更新分类状态失败:', error)
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 设置分页参数
     * @param {number} page 页码
     * @param {number} size 每页大小
     */
    const setPagination = (page, size) => {
        currentPage.value = page
        pageSize.value = size
    }

    /**
     * 重置状态
     */
    const resetState = () => {
        categories.value = []
        categoryTree.value = []
        currentCategory.value = null
        loading.value = false
        total.value = 0
        currentPage.value = 1
        pageSize.value = 10
    }

    /**
     * 根据父分类ID获取子分类
     * @param {number} parentId 父分类ID
     */
    const getChildCategories = (parentId = 0) => {
        return categories.value.filter(category => category.parentId === parentId)
    }

    /**
     * 获取分类层级显示名称
     * @param {Object} category 分类对象
     */
    const getCategoryDisplayName = (category) => {
        if (!category) return ''

        const levelPrefix = '　'.repeat((category.level - 1) * 2)
        return `${levelPrefix}${category.name}`
    }

    return {
        // 状态
        categories,
        categoryTree,
        currentCategory,
        loading,
        total,
        currentPage,
        pageSize,

        // 计算属性
        categoryCount,
        hasCategories,

        // 方法
        getCategoryList,
        getCategoryTree,
        getCategoryDetail,
        createCategory,
        updateCategory,
        deleteCategory,
        updateCategoryStatus,
        setPagination,
        resetState,
        getChildCategories,
        getCategoryDisplayName
    }
})
